package com.yu.admin.common.util.session;

import com.yu.admin.modules.system.pojo.dto.SysUserDTO;
import com.yu.common.constant.Const;
import com.yu.common.exception.ServiceException;
import com.yu.common.service.RedisService;
import com.yu.common.util.jwt.JWTUtil;
import com.yu.common.util.servlet.ServletUtils;
import com.yu.common.util.spring.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Slf4j
public class AdminSessionUtil {
    private static final RedisService redisService = SpringContextUtil.getBeanByClass(RedisService.class);

    /**
     * 添加会话缓存  缓存到redis里，CONST_sys_user_redis_prefix + token 作为key
     */
    public static void setSysUserSession(SysUserDTO sysUserDTO) {
        sysUserDTO.setToken(JWTUtil.generateTokenWithUserId(sysUserDTO.getId()));
        redisService.set(Const.CONST_sys_user_session_redis_prefix + sysUserDTO.getId(), sysUserDTO, Const.CONST_one_week);
        log.info("[添加会话缓存] {}", sysUserDTO);
    }

    public static void updateSysUserSession(SysUserDTO sysUserDTO) {
        redisService.set(Const.CONST_sys_user_session_redis_prefix + sysUserDTO.getId(), sysUserDTO, Const.CONST_one_week);
        log.info("[更新会话缓存] {}", sysUserDTO); // 更新会话缓存
    }

    public static void updateSysUserSession(String token) throws ServiceException {
        redisService.expire(Const.CONST_sys_user_session_redis_prefix + JWTUtil.getSysUserId(token), Const.CONST_one_week);
        log.info("[更新会话缓存] {}", token); // 延长时间
    }

    public static SysUserDTO getCurrentSysUser() throws ServiceException {
        return (SysUserDTO) redisService.get(Const.CONST_sys_user_session_redis_prefix + JWTUtil.getSysUserId(getToken()));
    }

    public static Integer getCurrentSysUserId() throws ServiceException {
        return JWTUtil.getSysUserId(getToken());
    }


    public static String getToken(HttpServletRequest request) throws ServiceException {
        String token = request.getParameter("token");
        if (StringUtils.isEmpty(token))
            token = request.getHeader(Const.CONST_token);
        if (token == null)
            throw ServiceException.CONST_user_not_login;
        return token;
    }

    public static String getToken() throws ServiceException {
        return getToken(ServletUtils.getRequest());
    }

    /**
     * 是否含有某项权限
     *
     * @param needPermission 标匹配权限 eg: system:user:update
     * @param token          令牌
     * @return boolean
     */
    public static boolean hasPermission(String needPermission, String token) throws ServiceException {
        if (StringUtils.isEmpty(needPermission))
            return true;

        // 拥有的权限
        for (String userPermission : getCurrentSysUser().getPermissions()) {
            if (userPermission.startsWith(needPermission) || "*".equals(userPermission))
                return true;
        }
        return false;
    }
}
